package com.mysy.hospital.controller;

import com.mysy.hospital.pojo.User;
import com.mysy.hospital.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JasonYu
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 用户登录判断
     * @param username 登录名
     * @param password 密码
     * @return user
     */
    @RequestMapping("login")
    public String login(String username, String password, Model model,
                        HttpServletRequest request, HttpServletResponse response) {

        //从表单获取输入的验证码
        String checkCode = request.getParameter("checkCode");
        //获取随机生成的验证码
        String imageCode = (String) request.getSession().getAttribute("checkcode_session");
        //判断两次输入的验证码是否相同
        if (!checkCode.equals(imageCode)) {
            model.addAttribute("msg","验证码不一致");
            return "forward:/login.jsp";
        }

        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);

        //查询数据库
        User user = userService.login(loginUser);
        //代表登录成功
        if (user != null) {
            //判断用户是否记住密码
            String remember = request.getParameter("remember");
            if ("yes".equals(remember)) {
                Cookie nameCookie = new Cookie("username", user.getUsername());
                nameCookie.setMaxAge(60*60*24*3);
                Cookie pwdCookie = new Cookie("password", user.getPassword());
                pwdCookie.setMaxAge(60*60*24*3);
                //将cookie放入客户端
                response.addCookie(nameCookie);
                response.addCookie(pwdCookie);
            }
            //将当前用户添加在session中
            model.addAttribute("user",user);
        } else {
            //登录失败 重新跳转至登录界面
            return "redirect:/login.jsp";
        }
        return "index";
    }
}
